package com.lwq.lwqmicoservice.framework.service;

import com.lwq.lwqmicoservice.common.model.Dto;
import com.lwq.lwqmicoservice.common.model.SysPermission;
import com.lwq.lwqmicoservice.common.model.SysRole;
import com.lwq.lwqmicoservice.framework.mapper.PermissionMapper;
import com.lwq.lwqmicoservice.framework.mapper.RoleMapper;
import com.lwq.lwqmicoservice.framework.mapper.UserMapper;
import com.lwq.lwqmicoservice.framework.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2021/6/10
 */
@Service
public class PermissionService {

    @Autowired
    private PermissionMapper mapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RedisUtil redis;

    /**
     * 接口两用,如已经查过roleId集合 则直接使用
     *
     * @param userId
     * @param ids
     * @return
     */
    public List<SysPermission> getPermissionsByUser(Long userId, List<Long> ids) {
        List<Long> roleList;
        if (ids == null || ids.isEmpty()) {
            roleList = roleMapper.getRoleIdByUserId(userId, SysRole.ENABLE);
        } else {
            roleList = ids;
        }
        if (!roleList.isEmpty()) {
            return mapper.getPermissionByRoleIds(roleList.stream().map(x -> x + "").collect(Collectors.joining(", ")));
        } else {
            return new ArrayList<>();
        }
    }

    public List<SysPermission> getAllPermissions(Dto dto) {
        return dto == null ? mapper.selectList(null) :
                mapper.selectByMap(dto);
    }

}
